package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<T> implements Delayed {


    private Long deadLineNanos;
    private T data;


    public DelayTask(Duration duration, T data){
        this.deadLineNanos = System.nanoTime()+duration.toNanos();
        this.data = data;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(),0),TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
       long diff = this.getDelay(TimeUnit.NANOSECONDS)- o.getDelay(TimeUnit.NANOSECONDS);
       if (diff>0){
           return 1;
       } else if (diff==0) {
           return 0;
       }else{
           return -1;
       }
    }
}
